package com.ruoyi.framework.shiro.web.filter;

import com.ruoyi.common.utils.StringUtils;
import org.apache.shiro.web.filter.authz.AuthorizationFilter;
import org.apache.shiro.web.servlet.ShiroHttpServletRequest;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.http.HttpStatus;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author Alan Zhang
 * @Date 2021/10/4 15:33
 */
public class ApiAuthorizationFilter extends AuthorizationFilter {
    @Override
    protected boolean isAccessAllowed(ServletRequest servletRequest, ServletResponse servletResponse, Object o) throws Exception {
        String token = ((ShiroHttpServletRequest) servletRequest).getHeader("token");
        System.out.println("token =========="+token);
        if(StringUtils.isNotEmpty(token)){
            if(token.length() < 13){
                return false;
            } else if(token.length() == 13) {
                long diffVal = System.currentTimeMillis() - Long.parseLong(token);
                System.out.println("diffVal =========="+diffVal);

                return true;
            } else {
                return true;
            }
        }
        return false;
    }

    /**
     * 权限校验失败，错误处理
     */
    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws IOException {
        HttpServletResponse httpResponse = WebUtils.toHttp(response);
        httpResponse.setCharacterEncoding("UTF-8");
        httpResponse.setContentType("application/json;charset=utf-8");
        httpResponse.setStatus(HttpStatus.UNAUTHORIZED.value());
        return false;
    }
}
